package com.rdc.rdcmusicapp.mainActivity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.animation.ObjectAnimator;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.rdc.rdcmusicapp.R;
import com.rdc.rdcmusicapp.bean.LocalMusicBean;
import com.rdc.rdcmusicapp.playingActivity.PlayingActivity;

import java.io.IOException;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import static com.rdc.rdcmusicapp.utils.PermissionUtils.verifyStoragePermissions;

/**
 * [主页面]
 *
 * @author Suzy.Mo
 * @createTime 2021/4/24 14:20
 */
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    ImageView nextIv, playIv, lastIv, albumIv;
    TextView singerTv, songTv, nowProTv, allProTv;
    SeekBar seekBar;
    RecyclerView musicRv;
    ObjectAnimator animator;
    private Thread thread;//线程
    private boolean isStop;//线程标志位
    List<LocalMusicBean> mDatas;//数据源
    private LocalMusicAdapter adapter;
    int mCurrentPlayPosition = -1;//记录当前正在播放的音乐的位置
    int mCurrentPausePositionInSong = 0;//记录暂停音乐时进度条的位置
    MediaPlayer mediaPlayer;

    //运用Handler中的handleMessage方法接收子线程传递的信息
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            // 将SeekBar位置设置到当前播放位置
            seekBar.setProgress(msg.what);
            //获得音乐的当前播放时间
            nowProTv.setText(formatime(msg.what));
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);
        verifyStoragePermissions(this);
        initView();
        mediaPlayer = new MediaPlayer();
        mDatas = new ArrayList<>();
        //设置旋转动画
        animator = ObjectAnimator.ofFloat(albumIv, "rotation", 0f, 360f);
        animator.setDuration(5000);// 持续时间 - 决定了播放的快慢
        animator.setInterpolator(new LinearInterpolator());
        animator.setRepeatCount(-1);
        //创建适配器对象
        adapter = new LocalMusicAdapter(this, mDatas);
        musicRv.setAdapter(adapter);
        //设置布局管理器
        LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        musicRv.setLayoutManager(layoutManager);
        //加载本地数据源
        loadLocalMusicData();
        //设置每一项的点击事件
        setEventListener();
        //设置自动播放的监听
        mediaPlayer.setOnCompletionListener(new InnerOnCompletionListener());
        //监听滚动条事件
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                //参数 ： fromUser即b 是用来标识是否来自用户的手动操作  true 用户动过手动方式更改的进度条
                if (b) {
                    //seekto方法是异步方法
                    //seekto方法的参数是毫秒，而不是秒
                    mediaPlayer.seekTo(i);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.local_music_bottom_iv_last:
                if (mCurrentPlayPosition == 0) {
                    Toast.makeText(this, "已经是第一首了，没有上一曲！", Toast.LENGTH_SHORT).show();
                    return;
                }
                mCurrentPlayPosition = mCurrentPlayPosition - 1;
                LocalMusicBean lastBean = mDatas.get(mCurrentPlayPosition);
                playMusicBean(lastBean);
                break;
            case R.id.local_music_bottom_iv_next:
                playNextSong();
                break;
            case R.id.local_music_bottom_iv_play:
                if (mCurrentPlayPosition == -1) {
                    //并没有选中要播放的音乐
                    Toast.makeText(this, "请选择想要播放的音乐", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (mediaPlayer.isPlaying()) {
                    //此时处于播放状态，需要暂停音乐
                    pauseMusic();
                } else {
                    //此时没有播放音乐，点击开始播放音乐，同时开始旋转
                    playMusic();
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                        animator.resume();
                    }
                }
                break;
        }
    }

    /**
     * @param
     * @return
     * @description 设置每一项的点击事件
     * @author Suzy.Mo
     * @time 2021/4/24
     */
    private void setEventListener() {
        adapter.setOnItemClickListener(new LocalMusicAdapter.OnItemClickListener() {
            @Override
            public void OnItemClick(View view, int position) {
                mCurrentPlayPosition = position;
                LocalMusicBean musicBean = mDatas.get(position);
                playMusicBean(musicBean);
            }
        });
    }

    /**
     * @param
     * @return
     * @description 点击播放按钮播放音乐，或者暂停从新播放
     * @author Suzy.Mo
     * @time 2021/4/24
     */
    public void playMusic() {
        if (mediaPlayer != null && !mediaPlayer.isPlaying()) {
            if (mCurrentPausePositionInSong == 0) {
                try {
                    mediaPlayer.prepare();
                    mediaPlayer.start();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                //从暂停到播放
                mediaPlayer.seekTo(mCurrentPausePositionInSong);
                mediaPlayer.start();
            }
            //设置seekbar的最大值
            seekBar.setMax(mediaPlayer.getDuration());
            //创建一个线程
            thread = new Thread(new MusicThread());
            //启动线程
            thread.start();
            playIv.setImageResource(R.mipmap.icon_pause);
        }
    }
    /**
     * @description 时间转换类，将得到的音乐时间毫秒转换为时分秒格式
     * @param length
     * @return totalTime
     * @author Suzy.Mo
     * @time  2021/4/25
     */
    private String formatime(int length) {
        Date date = new Date(length);
        SimpleDateFormat sdf = new SimpleDateFormat("mm:ss");
        String totalTime = sdf.format(date);
        return totalTime;
    }

    /**
     * @param
     * @return
     * @description 暂停音乐的函数
     * @author Suzy.Mo
     * @time 2021/4/24
     */
    public void pauseMusic() {
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            mCurrentPausePositionInSong = mediaPlayer.getCurrentPosition();
            mediaPlayer.pause();
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                animator.pause();
            }
            playIv.setImageResource(R.mipmap.icon_play);
        }
    }

    /**
     * @param
     * @return
     * @description 停止音乐的函数
     * @author Suzy.Mo
     * @time 2021/4/24
     */
    public void stopMusic() {
        if (mediaPlayer != null) {
            mCurrentPausePositionInSong = 0;  //把进度条拉回0
            mediaPlayer.pause();
            mediaPlayer.seekTo(0);
            mediaPlayer.stop();
            playIv.setImageResource(R.mipmap.icon_play);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopMusic();
    }

    /**
     * @param musicBean
     * @return
     * @description 根据传入对象播放音乐
     * @author Suzy.Mo
     * @time 2021/4/24
     */
    public void playMusicBean(LocalMusicBean musicBean) {
//      设置底部显示的歌手名称和歌曲名
        singerTv.setText(musicBean.getmSinger());
        songTv.setText(musicBean.getmSong());
        allProTv.setText(musicBean.getmDuration());
        stopMusic();
        //重置多媒体播放器
        mediaPlayer.reset();
        //设置新的路径
        try {
            mediaPlayer.setDataSource(musicBean.getmPath());
            playMusic();
            animator.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * @param
     * @return
     * @description 加载本地存储当中的音乐mp3文件到集合当中
     * @author Suzy.Mo
     * @time 2021/4/24
     */
    public void loadLocalMusicData() {
//        1.获取ContentResolver对象
        ContentResolver resolver = getContentResolver();
//        2.获取本地音乐存储的Uri地址
        Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
//        3 开始查询地址
        Cursor cursor = resolver.query(uri, null, null, null, null);
//        4.遍历Cursor
        int id = 0;
        while (cursor.moveToNext()) {
            String song = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
            String singer = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));
            String album = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM));
            id++;
            String sid = String.valueOf(id);
            String path = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
            long duration = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.DURATION));
            SimpleDateFormat sdf = new SimpleDateFormat("mm:ss");
            String time = sdf.format(new Date(duration));
//          将一行当中的数据封装到对象当中
            LocalMusicBean bean = new LocalMusicBean(sid, song, singer, album, time, path);
            mDatas.add(bean);
        }
//      数据源变化，提示适配器更新
        adapter.notifyDataSetChanged();
    }


    /**
     * @param
     * @return
     * @description 初始化控件的函数
     * @author Suzy.Mo
     * @time 2021/4/24
     */
    private void initView() {
        nextIv = findViewById(R.id.local_music_bottom_iv_next);
        playIv = findViewById(R.id.local_music_bottom_iv_play);
        lastIv = findViewById(R.id.local_music_bottom_iv_last);
        albumIv = findViewById(R.id.local_music_bottom_iv_icon);
        singerTv = findViewById(R.id.local_music_bottom_tv_singer);
        songTv = findViewById(R.id.local_music_bottom_tv_song);
        musicRv = findViewById(R.id.local_music_rv);
        nowProTv = findViewById(R.id.nowProTv);
        allProTv = findViewById(R.id.allProTv);
        seekBar = findViewById(R.id.mainSeekBar);
        nextIv.setOnClickListener(this);
        lastIv.setOnClickListener(this);
        playIv.setOnClickListener(this);
    }

    /**
     * @param
     * @return
     * @description 播放下一首
     * @author Suzy.Mo
     * @time
     */
    private void playNextSong() {
        if (mCurrentPlayPosition == mDatas.size() - 1) {
            Toast.makeText(MainActivity.this, "已经是最后一首了，没有下一曲！", Toast.LENGTH_SHORT).show();
            return;
        }
        mCurrentPlayPosition = mCurrentPlayPosition + 1;
        LocalMusicBean nextBean = mDatas.get(mCurrentPlayPosition);
        playMusicBean(nextBean);
    }

    /**
     * @param
     * @author Suzy.Mo
     * @description 监听音乐播放完成的方法
     * @return
     * @time 2021/4/24
     */
    private final class InnerOnCompletionListener implements MediaPlayer.OnCompletionListener {

        @Override
        public void onCompletion(MediaPlayer mediaPlayer) {
            playNextSong();
        }
    }

    /**
     * @param view
     * @return
     * @description 底部播放栏进行页面跳转的监听设置
     * @author Suzy.Mo
     * @time 2021/4/24
     */
    public void ButtonLayoutClick(View view) {
        if (mCurrentPlayPosition == -1) {
//          并没有选中要播放的音乐
            Toast.makeText(this, "请选择想要播放的音乐", Toast.LENGTH_SHORT).show();
            return;
        }
        Intent intent = new Intent(this, PlayingActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("song", mDatas.get(mCurrentPlayPosition));// 添加歌曲
        intent.putExtras(bundle);
        startActivity(intent);
    }

    /**
     * @param
     * @author Suzy.Mo
     * @description 建立子线程的函数
     * @return
     * @time
     */
    class MusicThread implements Runnable {

        @Override
        //实现run方法
        public void run() {
            //判断音乐的状态，在不停止与不暂停的情况下向总线程发出信息
            while (mediaPlayer != null && isStop == false) {

                try {
                    //每100毫秒更新一次位置
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //发出的信息
                handler.sendEmptyMessage(mediaPlayer.getCurrentPosition());
            }
        }
    }
}